package com.open.cloud.rbac.service.user.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.crypto.digest.DigestUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.open.cloud.rbac.entity.config.CoreSystemConfig;
import com.open.cloud.rbac.entity.orgpost.CoreUserOrgRel;
import com.open.cloud.rbac.entity.orgpost.CoreUserPostRel;
import com.open.cloud.rbac.entity.user.CoreUser;
import com.open.cloud.rbac.entity.user.CoreUserLoginInfo;
import com.open.cloud.rbac.mapper.config.CoreSystemConfigMapper;
import com.open.cloud.rbac.mapper.orgpost.CoreOrganizationMapper;
import com.open.cloud.rbac.mapper.orgpost.CoreUserOrgRelMapper;
import com.open.cloud.rbac.mapper.orgpost.CoreUserPostRelMapper;
import com.open.cloud.rbac.mapper.user.CoreUserLoginInfoMapper;
import com.open.cloud.rbac.mapper.user.CoreUserMapper;
import com.open.cloud.rbac.object.user.CoreUserDto;
import com.open.cloud.rbac.object.user.CoreUserSelectDto;
import com.open.cloud.rbac.object.user.CoreUserVo;
import com.open.cloud.rbac.service.user.ICoreUserService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author wangzengzhou01
 * @since 2024-12-23
 */
@Service
public class CoreUserServiceImpl extends ServiceImpl<CoreUserMapper, CoreUser>
        implements ICoreUserService {

    @Resource
    private CoreUserMapper userMapper;

    @Resource
    private Snowflake snowflake;

    @Resource
    private CoreOrganizationMapper orgMapper;

    @Value("${user.login.default.pwkey}")
    private String defaultPwKey;


    @Value("${user.login.default.password}")
    private String defaultPassword;

    @Resource
    private CoreSystemConfigMapper systemConfigMapper;

    @Resource
    private CoreUserLoginInfoMapper userLoginInfoMapper;

    @Resource
    private CoreUserOrgRelMapper userOrgRelMapper;

    @Resource
    private CoreUserPostRelMapper userPostRelMapper;


    /**
     * 分页查询用户
     *
     * @param userSelectDto
     * @return
     */
    @Override
    public IPage<CoreUserVo> getUserByPage(CoreUserSelectDto userSelectDto) {
        String orgId = userSelectDto.getOrgId();
        List<String> orgList = new ArrayList<>();
        if (ObjectUtils.isNotEmpty(orgId)) {
            orgList = orgMapper.selectOrgIdsByParentId(orgId);
            orgList.add(orgId);
        }
        QueryWrapper<CoreUser> queryWrapper = Wrappers.<CoreUser>query()
                .eq(ObjectUtils.isNotEmpty(userSelectDto.getCompanyId()), "cu.company_id", userSelectDto.getCompanyId())
                .eq(ObjectUtils.isNotEmpty(userSelectDto.getPostId()), "cu.", userSelectDto.getPostId())
                .like(ObjectUtils.isNotEmpty(userSelectDto.getUserName()), "cu.nick_name", userSelectDto.getUserName())
                .like(ObjectUtils.isNotEmpty(userSelectDto.getLoginName()), "culi.user_login_name", userSelectDto.getLoginName())
                .in(orgList.size() > 0, "cuor.org_id", orgList)
                .ne("culi.`status`", "4")
                .orderByDesc("cu.create_time");

        IPage<CoreUser> page = new Page<>(userSelectDto.getPageNo(), userSelectDto.getPageSize());

        IPage<CoreUserVo> data = userMapper.selectUserVo(page, queryWrapper);

        return data;
    }

    /**
     * 创建用户信息
     *
     * @param userDto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public JSONObject createUserInfo(CoreUserDto userDto) {
        JSONObject result = new JSONObject();

        LambdaQueryWrapper<CoreUserLoginInfo> loginQuery = Wrappers.<CoreUserLoginInfo>lambdaQuery()
                .eq(CoreUserLoginInfo::getUserLoginName, userDto.getUserLoginName())
                .ne(CoreUserLoginInfo::getStatus, "4");
        List<CoreUserLoginInfo> loginList = userLoginInfoMapper.selectList(loginQuery);
        if (loginList.size() > 0) {
            result.put("code", 500);
            result.put("message", "创建失败，用户账号不唯一");
        } else {
            String defaultPwd = defaultPassword;
            QueryWrapper sysQuery = Wrappers.<CoreSystemConfig>query()
                    .eq("config_key", defaultPwKey);
            CoreSystemConfig systemConfig = systemConfigMapper.selectOne(sysQuery);
            if (ObjectUtils.isNotEmpty(systemConfig)) {
                defaultPwd = systemConfig.getConfigValue();
            }
            CoreUserLoginInfo userLoginInfo = new CoreUserLoginInfo();
            userLoginInfo.setId(snowflake.nextIdStr());
            userLoginInfo.setUserLoginName(userDto.getUserLoginName());
            userLoginInfo.setUserLoginPassword(DigestUtil.md5Hex(defaultPwd));
            userLoginInfo.setLoginFailTimes(0);
            userLoginInfo.setInitPasswordFlag("1");
            userLoginInfo.setStatus(userDto.getStatus());
            userLoginInfo.setCreateTime(new Date());
            userLoginInfo.setUpdateTime(new Date());
            int loginUser = userLoginInfoMapper.insert(userLoginInfo);

            CoreUser coreUser = new CoreUser();
            coreUser.setId(snowflake.nextIdStr());
            coreUser.setUserLoginId(userLoginInfo.getId());
            coreUser.setNickName(userDto.getNickName());
            coreUser.setUserType("user");
            coreUser.setEmail(userDto.getEmail());
            coreUser.setPhoneNumber(userDto.getPhoneNumber());
            coreUser.setSex(userDto.getSex());
            coreUser.setAvatar(userDto.getAvatar());
            coreUser.setCompanyId(userDto.getCompanyId());
            coreUser.setRemark(userDto.getRemark());
            coreUser.setCreateTime(new Date());
            coreUser.setCreateBy("admin");
            coreUser.setUpdateTime(new Date());
            coreUser.setUpdateBy("admin");
            int user = userMapper.insert(coreUser);

            if (loginUser > 0 && user > 0) {
                result.put("code", 200);
                result.put("message", "创建成功");
            } else {
                result.put("code", 500);
                result.put("message", "创建失败");
            }

            CoreUserOrgRel userOrgRel = new CoreUserOrgRel();
            userOrgRel.setId(snowflake.nextIdStr());
            userOrgRel.setUserId(coreUser.getId());
            userOrgRel.setOrgId(userDto.getOrgId());
            userOrgRel.setCreateTime(new Date());
            userOrgRelMapper.insert(userOrgRel);

            CoreUserPostRel userPostRel = new CoreUserPostRel();
            userPostRel.setId(snowflake.nextIdStr());
            userPostRel.setUserId(coreUser.getId());
            userPostRel.setPostId(userDto.getPostId());
            userPostRel.setCreateTime(new Date());
            userPostRelMapper.insert(userPostRel);
        }
        return result;
    }

    /**
     * 修改用户信息
     *
     * @param userDto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject changeUserInfo(CoreUserDto userDto) {

        CoreUser coreUser = new CoreUser();
        BeanUtils.copyProperties(userDto, coreUser);
        coreUser.setUpdateTime(new Date());
        coreUser.setUpdateBy("admin");
        int user = userMapper.updateById(coreUser);

        CoreUserLoginInfo userLoginInfo = new CoreUserLoginInfo();
        userLoginInfo.setId(coreUser.getUserLoginId());
        userLoginInfo.setStatus(userDto.getStatus());
        userLoginInfo.setUpdateTime(new Date());
        int loginUser = userLoginInfoMapper.updateById(userLoginInfo);

        LambdaQueryWrapper<CoreUserOrgRel> orgQuery = Wrappers.<CoreUserOrgRel>lambdaQuery()
                .eq(CoreUserOrgRel::getUserId, userDto.getId());
        userOrgRelMapper.delete(orgQuery);

        CoreUserOrgRel userOrgRel = new CoreUserOrgRel();
        userOrgRel.setId(snowflake.nextIdStr());
        userOrgRel.setUserId(coreUser.getId());
        userOrgRel.setOrgId(userDto.getOrgId());
        userOrgRel.setCreateTime(new Date());
        userOrgRelMapper.insert(userOrgRel);

        LambdaQueryWrapper<CoreUserPostRel> postQuery = Wrappers.<CoreUserPostRel>lambdaQuery()
                .eq(CoreUserPostRel::getUserId, userDto.getId());
        userPostRelMapper.delete(postQuery);

        CoreUserPostRel userPostRel = new CoreUserPostRel();
        userPostRel.setId(snowflake.nextIdStr());
        userPostRel.setUserId(coreUser.getId());
        userPostRel.setPostId(userDto.getPostId());
        userPostRel.setCreateTime(new Date());
        userPostRelMapper.insert(userPostRel);

        JSONObject result = new JSONObject();
        if (loginUser > 0 && user > 0) {
            result.put("code", 200);
            result.put("message", "创建成功");
        } else {
            result.put("code", 500);
            result.put("message", "创建失败");
        }

        return result;
    }

}
